package com.gitee.wsl.io.receiver

import com.gitee.wsl.io.div
import com.gitee.wsl.io.hex
import com.gitee.wsl.io.write
import kotlinx.io.bytestring.ByteString
import kotlinx.io.files.FileSystem
import kotlinx.io.files.Path
import kotlinx.io.write

/**
 * After getting a [ByteString], [Receiver]s are iteratively called in order to handle.
 */
internal interface Receiver {
    /**
     * Handle a [ByteString] which can include loading it into a [Zipline] runtime
     *  or saving to file system.
     */
    suspend fun receive(
        byteString: ByteString,
        id: String,
        sha256: ByteString,
    )
}

/**
 * Save [ZiplineFile] to file system.
 */
internal class FsSaveReceiver(
    private val downloadFileSystem: FileSystem,
    private val downloadDir: Path,
) : Receiver {
    override suspend fun receive(byteString: ByteString, id: String, sha256: ByteString) {
        downloadFileSystem.write(downloadDir / sha256.hex()) {
            write(byteString)
        }
    }
}